﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.DAO;
using StoreTransport.Data;
using StoreTransport.Business.Helper;
using StoreTransport.Business.Constants;
using StoreTransport.Resources;

namespace StoreTransport.Presentation.Forms {
    public partial class ProductListForm : Form {
        int id = 0;
        Dictionary<int, string> productLineDic = new Dictionary<int, string>();
        public ProductListForm() {
            InitializeComponent();
        }

        private void ProductListForm_Load(object sender, EventArgs e) {
            _tbxProductCode.Select();
            CommonHelper.SetValueForComboBox(_drpProductStatus, CommonConstant.Status);

            StoreTransportDataContext context = CommonHelper.GetContext();
            _drpProductKind.ValueMember = ColumnName.ID;
            _drpProductKind.DisplayMember = ColumnName.ProductKindName;
            _drpProductKind.DataSource = context.ProductKinds.OrderBy(c => c.ProductKindName);

            _drpProductLine.DisplayMember = ColumnName.ProductLineName;
            _drpProductLine.ValueMember = ColumnName.ID;
            _drpProductLine.DataSource = context.ProductLines.OrderBy(c => c.ProductLineName);

            productLineDic = context.ProductLines.ToDictionary(c => c.ID, c => c.ProductLineName);
            LoadProductLists();
        }

        private void LoadProductLists() {
            _grdProduct.AutoGenerateColumns = false;
            IEnumerable<Product> productList = null;
            StoreTransportDataContext context = CommonHelper.GetContext();
            if (_cbxShowInvalidProduct.Checked) {
                var invalidChar = ValidData.I.ToString()[0];
                productList = context.Products.Where(c => c.ValidData.Equals(invalidChar)).Cast<Product>();
            } else {
                if (_drpProductKind.Items.Count > 0) {
                    //List<int> kindIds = ((List<ProductKind>) _drpProductKind.DataSource).Select(c => c.ID).ToList();
                    List<int> kindIds = new List<int>();
                    foreach (var kind in _drpProductKind.Items) {
                        kindIds.Add((kind as ProductKind).ID);
                    }
                    productList = context.Products.Where(c => c.ProductKind.HasValue &&
                        kindIds.Contains(c.ProductKind.Value)).Cast<Product>();
                } else {
                    productList = context.Products.Cast<Product>();
                }
            }
            productList = productList.OrderBy(c => c.Status).
                ThenBy(c => c.ProductKind).ThenBy(c => c.ProductCode);
            List<PresentProductDTO> pProductList = new List<PresentProductDTO>();
            foreach (Product p in productList) {
                string productLineName = string.Empty;
                //productLineDic.TryGetValue(p.ProductKind1.ProductLine, out productLineName);
                string prolineName = string.Empty;
                string prokindName = string.Empty;
                if (p.ProductKind1 != null) {
                    prokindName = p.ProductKind1.ProductKindName;
                    prolineName = p.ProductKind1.ProductLine1.ProductLineName;
                }
                pProductList.Add(new PresentProductDTO(p.ID, p.ProductCode, prolineName,
                    p.ProductName, prokindName, CommonHelper.GetEnumValue(p.Status, CommonConstant.StatusDic)));
            }
            _grdProduct.DataSource = pProductList.OrderBy(c => c.Status).
                ThenBy(c => c.ProductLine).ThenBy(c=> c.ProductKind).ThenBy(c => c.ProductCode).ToList();
        }

        private void _btxCreate_Click(object sender, EventArgs e) {
            id = 0;
            _tbxProductCode.Select();
            _tbxProductCode.ReadOnly = false;
            _tbxProductCode.Text = string.Empty;
            _tbxProductName.Text = string.Empty;
            CommonHelper.ResetCombobox(_drpProductStatus);
            CommonHelper.ResetCombobox(_drpProductLine);
            //CommonHelper.ResetCombobox(_drpProductKind);
        }

        private void _btnDelete_Click(object sender, EventArgs e) {
            if (_grdProduct.SelectedRows.Count > 0) {
                DialogResult result = MessageBox.Show(StoreTransportResource.Message_ConfirmDelete,
                    StoreTransportResource.MessageBox_ConfirmDelete, MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes) {
                    try {
                        StoreTransportDataContext context = CommonHelper.GetContext();
                        foreach (DataGridViewRow row in _grdProduct.SelectedRows) {
                            id = int.Parse(row.Cells[0].Value.ToString());
                            Product selectedItem = context.Products.Where(c => c.ID == id).First();
                            context.Products.DeleteOnSubmit(selectedItem);
                            context.SubmitChanges();
                        }
                        LoadProductLists();
                        id = 0;
                    } catch (Exception ex) {
                        MessageBox.Show(StoreTransportResource.ErrorMessage_CanNotDeleteItem);
                    }
                }
            } else {
                MessageBox.Show(StoreTransportResource.NoItemSelected);
            }
        }

        private void _btxEdit_Click(object sender, EventArgs e) {
            if (_grdProduct.SelectedRows.Count > 0) {
                id = int.Parse(_grdProduct.SelectedRows[0].Cells[0].Value.ToString());
                EditItem();
            }
        }

        private void EditItem() {
            StoreTransportDataContext context = CommonHelper.GetContext();
            Product selectedItem = context.Products.Where(c => c.ID.Equals(id)).First();
            CommonHelper.SetComboboxValue(_drpProductStatus, selectedItem.Status.ToString());
            int productKindID = 0;
            int lineID = 0;
            if (selectedItem.ProductKind != null) {
                productKindID = selectedItem.ProductKind.Value;
                lineID = selectedItem.ProductKind1.ProductLine;
                _drpProductLine.SelectedValue = context.ProductLines.Where(c => c.ID == lineID).First().ID;
                CommonHelper.SetComboboxValue(_drpProductKind, productKindID);
            }
            _tbxProductCode.ReadOnly = true;
            _tbxProductCode.Text = selectedItem.ProductCode;
            _tbxProductName.Text = selectedItem.ProductName;
        }

        private void _btxSave_Click(object sender, EventArgs e) {
            string errorMessage = CommonHelper.CheckRequiredField(_tbxProductCode.Text, _lblProductCode.Text);
            errorMessage += CommonHelper.CheckRequiredField(_tbxProductName.Text, _lblProductName.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage, StoreTransportResource.ErrorMessage_ErrorMessageTitle);
                return;
            }
            StoreTransportDataContext context = CommonHelper.GetContext();
            Product p = new Product();
            if (id != 0) {
                var item = context.Products.First(c => c.ProductCode.Equals(_tbxProductCode.Text) &&
                   c.ProductName.Equals(_tbxProductName.Text));
                if (item != null && item.ID != id) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Product,
                        _tbxProductCode.Text, _tbxProductName.Text));
                    return;
                }
                p = context.Products.Where(c => c.ID == id).First();
            } else {
                if (context.Products.FirstOrDefault(c => c.ProductCode.Equals(_tbxProductCode.Text) &&
                    c.ProductName.Equals(_tbxProductName.Text)) != null) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Product,
                        _tbxProductCode.Text, _tbxProductName.Text));
                    return;
                }
                context.Products.InsertOnSubmit(p);
            }
            p.ProductCode = _tbxProductCode.Text;
            p.ProductName = _tbxProductName.Text;
            p.Status = _drpProductStatus.SelectedValue.ToString()[0];
            p.ValidData = ValidData.V.ToString()[0];
            p.ProductKind = int.Parse(_drpProductKind.SelectedValue.ToString());

            context.SubmitChanges();
            LoadProductLists();
        }

        private void _btnRefreshList_Click(object sender, EventArgs e) {
            LoadProductLists();
        }

        private void _grdProduct_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            id = int.Parse(_grdProduct.Rows[e.RowIndex].Cells[0].Value.ToString());
            EditItem();
        }

        private void _drpProductLine_SelectedIndexChanged(object sender, EventArgs e) {
            StoreTransportDataContext context = CommonHelper.GetContext();
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            var dataSource = context.ProductKinds.Where(c => c.ProductLine == pl.ID)
                .OrderBy(pk => pk.ProductKindName);
            _drpProductKind.Text = string.Empty;
            _drpProductKind.DisplayMember = ColumnName.ProductKindName;
            _drpProductKind.ValueMember = ColumnName.ID;
            _drpProductKind.DataSource = dataSource;
            LoadProductLists();
        }
    }
}
